//
//  GQHDriverAuthorizationSubController.m
//  Xanthium
//
//  Created by GuanQinghao on 02/04/2018.
//  Copyright © 2018 GuanQinghao. All rights reserved.
//

#pragma mark Macro
#import "GQHHeader.h"

#pragma mark Model

#pragma mark Object

#pragma mark View
#import "GQHDriverAuthorizationSubView.h"
#import "GQHCustomCell.h"

#pragma mark Controller
#import "GQHDriverAuthorizationSubController.h"

#import "GQHAgreementController.h"

#pragma mark CocoaPods
#import <TZImagePickerController.h>

#pragma mark ----------Header End----------

@interface GQHDriverAuthorizationSubController () <GQHDriverAuthorizationSubViewDelegate,TZImagePickerControllerDelegate> {
    
#pragma mark Data
    /// 图片
    UIImage *image0;
    UIImage *image1;
    UIImage *image2;
    UIImage *image3;
    UIImage *image4;
    UIImage *image5;
    UIImage *image6;
    UIImage *image7;
#pragma mark View
    /// 自定义根视图
    GQHDriverAuthorizationSubView *rootView;
}

@end


@implementation GQHDriverAuthorizationSubController

#pragma mark --Lifecycle
- (void)loadView {
    DLog();
    
    rootView = [[GQHDriverAuthorizationSubView alloc] initWithFrame:[UIScreen mainScreen].bounds];
    rootView.qh_delegate = self;
    self.view = rootView;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    DLog();
    
}

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    DLog();
    
    self.qh_titleLabel.text = @"上传证照信息";
    [self.qh_rightButton setHidden:YES];
    self.automaticallyAdjustsScrollViewInsets = NO;
}

- (void)viewDidAppear:(BOOL)animated {
    [super viewDidAppear:animated];
    DLog();
    
}

#pragma mark --Delegate
- (void)qh_selectedRowWithTableView:(UITableView *)tableView atIndexPath:(NSIndexPath *)indexPath {
    
    switch (indexPath.row) {
            
        case 0: {
            
            /// 身份证正面
            GQH_WEAKSELF;
            TZImagePickerController *imagePickerController = [[TZImagePickerController alloc] initWithMaxImagesCount:1 delegate:self];
            imagePickerController.allowTakePicture = YES;
            [imagePickerController setDidFinishPickingPhotosHandle:^(NSArray<UIImage *> *photos, NSArray *assets, BOOL isSelectOriginalPhoto) {
                DLog(@"选择图片完成,上传图片");
                
                if (photos) {
                    
                    GQHTruckImagesCell *cell = [rootView.qh_tableView cellForRowAtIndexPath: indexPath];
                    cell.qh_rightImageView.image = image0 = [photos firstObject];
                    [rootView.qh_tableView reloadData];
                } else {
                    
                    [weakSelf showToastWithText:@"请选择一张身份证正面图片"];
                }
            }];
            
            [self presentViewController:imagePickerController animated:YES completion:nil];
        }
            break;
        case 1: {
            
            /// 身份证反面
            GQH_WEAKSELF;
            TZImagePickerController *imagePickerController = [[TZImagePickerController alloc] initWithMaxImagesCount:1 delegate:self];
            imagePickerController.allowTakePicture = YES;
            [imagePickerController setDidFinishPickingPhotosHandle:^(NSArray<UIImage *> *photos, NSArray *assets, BOOL isSelectOriginalPhoto) {
                DLog(@"选择图片完成,上传图片");
                
                if (photos) {
                    
                    GQHTruckImagesCell *cell = [rootView.qh_tableView cellForRowAtIndexPath: indexPath];
                    cell.qh_rightImageView.image = image1 = [photos firstObject];
                    [rootView.qh_tableView reloadData];
                } else {
                    
                    [weakSelf showToastWithText:@"请选择一张身份证反面图片"];
                }
            }];
            
            [self presentViewController:imagePickerController animated:YES completion:nil];
        }
            break;
        case 2: {
            
            /// 驾驶证
            GQH_WEAKSELF;
            TZImagePickerController *imagePickerController = [[TZImagePickerController alloc] initWithMaxImagesCount:1 delegate:self];
            imagePickerController.allowTakePicture = YES;
            [imagePickerController setDidFinishPickingPhotosHandle:^(NSArray<UIImage *> *photos, NSArray *assets, BOOL isSelectOriginalPhoto) {
                DLog(@"选择图片完成,上传图片");
                
                if (photos) {
                    
                    GQHTruckImagesCell *cell = [rootView.qh_tableView cellForRowAtIndexPath: indexPath];
                    cell.qh_rightImageView.image = image2 = [photos firstObject];
                    [rootView.qh_tableView reloadData];
                } else {
                    
                    [weakSelf showToastWithText:@"请选择一张驾驶证图片"];
                }
            }];
            
            [self presentViewController:imagePickerController animated:YES completion:nil];
        }
            break;
        case 3: {
            
            /// 从业资格证
            GQH_WEAKSELF;
            TZImagePickerController *imagePickerController = [[TZImagePickerController alloc] initWithMaxImagesCount:1 delegate:self];
            imagePickerController.allowTakePicture = YES;
            [imagePickerController setDidFinishPickingPhotosHandle:^(NSArray<UIImage *> *photos, NSArray *assets, BOOL isSelectOriginalPhoto) {
                DLog(@"选择图片完成,上传图片");
                
                if (photos) {
                    
                    GQHTruckImagesCell *cell = [rootView.qh_tableView cellForRowAtIndexPath: indexPath];
                    cell.qh_rightImageView.image = image3 = [photos firstObject];
                    [rootView.qh_tableView reloadData];
                } else {
                    
                    [weakSelf showToastWithText:@"请选择一张从业资格证图片"];
                }
            }];
            
            [self presentViewController:imagePickerController animated:YES completion:nil];
        }
            break;
        case 4: {
            
            /// 道路运输许可证
            GQH_WEAKSELF;
            TZImagePickerController *imagePickerController = [[TZImagePickerController alloc] initWithMaxImagesCount:1 delegate:self];
            imagePickerController.allowTakePicture = YES;
            [imagePickerController setDidFinishPickingPhotosHandle:^(NSArray<UIImage *> *photos, NSArray *assets, BOOL isSelectOriginalPhoto) {
                DLog(@"选择图片完成,上传图片");
                
                if (photos) {
                    
                    GQHTruckImagesCell *cell = [rootView.qh_tableView cellForRowAtIndexPath: indexPath];
                    cell.qh_rightImageView.image = image4 = [photos firstObject];
                    [rootView.qh_tableView reloadData];
                } else {
                    
                    [weakSelf showToastWithText:@"请选择一张道路运输许可证图片"];
                }
            }];
            
            [self presentViewController:imagePickerController animated:YES completion:nil];
        }
            break;
        case 5: {
            
            /// 行驶证
            GQH_WEAKSELF;
            TZImagePickerController *imagePickerController = [[TZImagePickerController alloc] initWithMaxImagesCount:1 delegate:self];
            imagePickerController.allowTakePicture = YES;
            [imagePickerController setDidFinishPickingPhotosHandle:^(NSArray<UIImage *> *photos, NSArray *assets, BOOL isSelectOriginalPhoto) {
                DLog(@"选择图片完成,上传图片");
                
                if (photos) {
                    
                    GQHTruckImagesCell *cell = [rootView.qh_tableView cellForRowAtIndexPath: indexPath];
                    cell.qh_rightImageView.image = image5 = [photos firstObject];
                    [rootView.qh_tableView reloadData];
                } else {
                    
                    [weakSelf showToastWithText:@"请选择一张行驶证图片"];
                }
            }];
            
            [self presentViewController:imagePickerController animated:YES completion:nil];
        }
            break;
        case 6: {
            
            /// 车辆照片
            GQH_WEAKSELF;
            TZImagePickerController *imagePickerController = [[TZImagePickerController alloc] initWithMaxImagesCount:2 delegate:self];
            imagePickerController.allowTakePicture = NO;
            [imagePickerController setDidFinishPickingPhotosHandle:^(NSArray<UIImage *> *photos, NSArray *assets, BOOL isSelectOriginalPhoto) {
                DLog(@"选择图片完成,上传图片");
                
                if (photos && 2 == photos.count) {
                    
                    GQHTruckImagesCell *cell = [rootView.qh_tableView cellForRowAtIndexPath: indexPath];
                    cell.qh_leftImageView.image = image6 = photos[0];
                    cell.qh_rightImageView.image = image7 = photos[1];
                    [rootView.qh_tableView reloadData];
                } else {
                    
                    [weakSelf showToastWithText:@"请选择两张车辆照片"];
                }
            }];
            
            [self presentViewController:imagePickerController animated:YES completion:nil];
        }
            break;
        default:
            break;
    }
}

-(void)qh_checkAgreement {
    DLog(@"查看平台认证协议");
    
    GQHAgreementController *agreementController = [[GQHAgreementController alloc] init];
    agreementController.qh_agreementType = GQHAgreementTypeAuthorization;
    [self presentViewController:agreementController animated:YES completion:nil];
}

- (void)qh_submitInformation {
    DLog(@"提交认证信息");
    
//    if (!image0) {
//
//        [self showToastWithText:@"请选择一张身份证正面图片"];
//        return;
//    }
//
//    if (!image1) {
//
//        [self showToastWithText:@"请选择一张身份证反面图片"];
//        return;
//    }
//
//    if (!image2) {
//
//        [self showToastWithText:@"请选择一张驾驶证图片"];
//        return;
//    }
    
    if (!image3) {
        
        [self showToastWithText:@"请选择一张从业资格证图片"];
        return;
    }
    
    if (!image4) {
        
        [self showToastWithText:@"请选择一张道路运输许可证图片"];
        return;
    }
    
//    if (!image5) {
//
//        [self showToastWithText:@"请选择一张行驶证图片"];
//        return;
//    }
//
//    if (!image6) {
//
//        [self showToastWithText:@"请选择两张车辆照片"];
//        return;
//    }
    
    [self qh_loadLoadingView];
    [self uploadImagesWithSuccess:^(NSNumber *code, NSString *message, NSDictionary *data) {
        
        [self qh_removedLoadingView];
        if (0 == [code integerValue]) {
            
            [[NSUserDefaults standardUserDefaults] setObject:@"02" forKey:USER_STATUS];
            [self showToastWithText:@"认证信息提交成功"];
            
            dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(2.0 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                
                [self.navigationController popToRootViewControllerAnimated:YES];
            });
        } else {
            
            [self showToastWithText:message];
        }
    }];
}

#pragma mark --TargetMethod

#pragma mark --PrivateMethod
/// 上传图片
- (void)uploadImagesWithSuccess:(void(^)(NSNumber *code, NSString *message, NSDictionary *data))success {
    
    NSString *APIURLString = [[NSString qh_APIURLString] stringByAppendingPathComponent:@"/myInformation/1/diverAut"];
    
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    manager.requestSerializer.timeoutInterval = 20;
    manager.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"text/plain", @"multipart/form-data", @"application/json", @"text/html", @"image/jpeg", @"image/png", @"application/octet-stream", @"text/json", nil];
    [manager POST:APIURLString parameters:_qh_parameters constructingBodyWithBlock:^(id<AFMultipartFormData>  _Nonnull formData) {
        
        NSData *image0Data = UIImagePNGRepresentation(image0);
        NSData *image1Data = UIImagePNGRepresentation(image1);
        NSData *image2Data = UIImagePNGRepresentation(image2);
        NSData *image3Data = UIImagePNGRepresentation(image3);
        NSData *image4Data = UIImagePNGRepresentation(image4);
        NSData *image5Data = UIImagePNGRepresentation(image5);
        NSData *image6Data = UIImagePNGRepresentation(image6);
        NSData *image7Data = UIImagePNGRepresentation(image7);
        
        NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
        formatter.dateFormat = @"yyyyMMddHHmmssSSS";
        NSString *name = [formatter stringFromDate:[NSDate date]];
        
        NSString *file0Name = [NSString stringWithFormat:@"%@0.png", name];
        NSString *file1Name = [NSString stringWithFormat:@"%@1.png", name];
        NSString *file2Name = [NSString stringWithFormat:@"%@2.png", name];
        NSString *file3Name = [NSString stringWithFormat:@"%@3.png", name];
        NSString *file4Name = [NSString stringWithFormat:@"%@4.png", name];
        NSString *file5Name = [NSString stringWithFormat:@"%@5.png", name];
        NSString *file6Name = [NSString stringWithFormat:@"%@6.png", name];
        NSString *file7Name = [NSString stringWithFormat:@"%@7.png", name];
        
        
        [formData appendPartWithFileData:image0Data name:@"positiveIdCard" fileName:file0Name mimeType:@"image/png"];
        [formData appendPartWithFileData:image1Data name:@"backIdCard" fileName:file1Name mimeType:@"image/png"];
        [formData appendPartWithFileData:image2Data name:@"qrivingLicPhoto" fileName:file2Name mimeType:@"image/png"];
        [formData appendPartWithFileData:image3Data name:@"qualCerPhoto" fileName:file3Name mimeType:@"image/png"];
        [formData appendPartWithFileData:image4Data name:@"roadTraCerLic" fileName:file4Name mimeType:@"image/png"];
        [formData appendPartWithFileData:image5Data name:@"carQrivingLicPhoto" fileName:file5Name mimeType:@"image/png"];
        [formData appendPartWithFileData:image6Data name:@"CarPhoto" fileName:file6Name mimeType:@"image/png"];
        [formData appendPartWithFileData:image7Data name:@"CarPhoto1" fileName:file7Name mimeType:@"image/png"];
        
    } progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        DLog(@"%@",responseObject);
        
        if (success) {
            
            NSNumber *responseCode = [responseObject objectForKey:@"code"];
            NSString *responseMessage = [responseObject objectForKey:@"msg"];
            NSDictionary *responseData = [responseObject objectForKey:@"data"];
            
            success(responseCode,responseMessage,responseData);
        }
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        
        NSString *errorString = [NSString stringWithFormat:@"网络出错:%@,code:%ld", error.domain, (long)error.code];
        [self showToastWithText:errorString];
    }];
}

#pragma mark --Setter

#pragma mark --Getter

#pragma mark --View

@end
